package com.xiantm.study.thread.towparsetermination;

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

public class CountupThread extends Thread {
    private long counter = 0;
    private volatile boolean shutdownRequested = false;
    private FileWriter fileWriter;

    public void shutdownRequest(){
        shutdownRequested = true;
        interrupt();
    }

    public boolean isShutdownRequested() {
        return shutdownRequested;
    }

    @Override
    public void run() {
        try {
            while (!isShutdownRequested()){
                    doWork();
            }
        } catch (InterruptedException ignored) { } finally {
            doShutDown();
        }
    }

    private void doWork() throws InterruptedException{
        counter++;
        System.out.println("doWork: counter = "+ counter);
        Thread.sleep(500);
    }

    private void doShutDown() {
        fileWriter = null;
        try {
            fileWriter = new FileWriter("counter.txt");
            fileWriter.write("" + counter);
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("doShutdown: counter = " + counter);
    }
}
